package vip.meeet.thread.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionPrinter {

    private int loopNum;

    private ReentrantLock lock;

    public ConditionPrinter(int loopNum, ReentrantLock lock) {
        this.loopNum = loopNum;
        this.lock = lock;
    }

    public void print(String message, Condition current, Condition next) {
        lock.lock();
        try {
            for (int i = 0; i < loopNum; i++) {
                try {
                    //当前线程等待唤醒
                    current.await();
                    //当前线程已经唤醒，执行打印
                    System.out.print(message);
                    //唤醒下一个线程
                    next.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition conditionA = lock.newCondition();
        Condition conditionB = lock.newCondition();
        Condition conditionC = lock.newCondition();
        ConditionPrinter conditionPrinter = new ConditionPrinter(5, lock);
        new Thread(() -> {
            conditionPrinter.print("a", conditionA, conditionB);
        }).start();
        new Thread(() -> {
            conditionPrinter.print("b", conditionB, conditionC);
        }).start();
        new Thread(() -> {
            conditionPrinter.print("c", conditionC, conditionA);
        }).start();
        //等打印a的线程启动后，主线程唤醒该线程
        try {
            Thread.sleep(100L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //需要拿到锁才能调用condition方法
        lock.lock();
        try {
            conditionA.signal();
        } finally {
            lock.unlock();
        }
    }
}
